using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class UIFontReplaceTool
{
    [MenuItem("[FutureCore]/UI/替换所有界面预设的字体", false, 0)]
    private static void Find()
    {
        List<string> replaceFontList = new List<string> { "Arial", "PreMSYH", "MSYH", "ARIBLK", "HKBDT_W12" };

        if (!(Selection.activeObject is Font))
        {
            EditorUtility.DisplayDialog("错误", "请选择正确的字体", "确定");
            return;
        }

        Font newFont = Selection.activeObject as Font;

        if (!EditorUtility.DisplayDialog("提示", "确定替换全部字体为" + newFont.name, "确定", "取消"))
            return;

        List<string> withoutExtensions = new List<string>() { ".prefab" };
        string[] files1 = Directory.GetFiles(Application.dataPath + "/_Game/Resources/Module", "*.*", SearchOption.AllDirectories)
            .Where(s => withoutExtensions.Contains(Path.GetExtension(s).ToLower())).ToArray();
        string[] files = new string[files1.Length];
        files1.CopyTo(files, 0);

        int startIndex = 0;
        EditorApplication.update = delegate ()
        {
            string file = files[startIndex];

            bool isCancel = EditorUtility.DisplayCancelableProgressBar("字体替换...", file, startIndex / (float)files.Length);
            GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(GetRelativeAssetsPath(file));

            Text[] array = go.GetComponentsInChildren<Text>(true);
            List<Text> list = new List<Text>(array);
            list.ForEach(i =>
            {
                if (i.font == null)
                {
                    return;
                }

                if (replaceFontList.Contains(i.font.name))
                {
                    if (i.font != newFont)
                    {
                        i.font = newFont;
                        EditorUtility.SetDirty(i);
                    }
                }
            });

            startIndex++;
            if (isCancel || startIndex >= files.Length)
            {
                EditorUtility.ClearProgressBar();
                EditorApplication.update = null;
                startIndex = 0;

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                Debug.Log("全部字体替换完成");
            }
        };
    }

    private static string GetRelativeAssetsPath(string path)
    {
        return "Assets" + Path.GetFullPath(path).Replace(Path.GetFullPath(Application.dataPath), "").Replace('\\', '/');
    }
}